<template>
  <div class="app-container">
    <!-- 数据查询区：表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="餐台编号" prop="tableId">
        <el-input
          v-model="queryParams.tableId"
          placeholder="请输入餐台编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用状态" prop="tableStatus">
        <el-select v-model="queryParams.tableStatus" style="width: 200px" placeholder="请选择使用状态" @keyup.enter="handleQuery">
          <el-option label="空闲" value="空闲" />
          <el-option label="占用" value="占用" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据操作区：按钮 -->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Delete" @click="handleDeleteBatch" :disabled="!multiple">批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 数据展示区：表格 -->
    <el-table v-loading="loading" :data="tables" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="餐台编号" align="center" width="150" prop="tableId" />
      <el-table-column label="桌型" align="center" prop="tableType" />
      <el-table-column label="使用状态" align="center" width="150" prop="tableStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" size="small" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button link type="primary" icon="View" size="small" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 数据展示区：分页加载 -->
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- 数据编辑区：新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="餐台编号" prop="tableId">
          <el-input v-model="form.tableId" placeholder="请输入餐台编号" :disabled="isEditMode"/>
          <span v-if="isEditMode" class="tip-text">（餐台编号创建后不可修改）</span>
        </el-form-item>
        <el-form-item label="桌型" prop="tableType">
          <el-select v-model="form.tableType" placeholder="请选择桌型">
            <el-option label="小桌(1-2人)" value="小桌" />
            <el-option label="中桌(3-4人)" value="中桌" />
            <el-option label="大桌(5-6人)" value="大桌" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用状态" prop="tableStatus">
          <el-switch 
          v-model="form.tableStatus" 
          :active-value="'空闲'"
          :inactive-value="'占用'"
          active-text="空闲" 
          inactive-text="占用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
          <el-button @click="resetForm(formRef)" v-show="form.tableId === undefined">重 置</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据查看区：抽屉 -->
    <el-drawer v-model="drawer" title="餐台信息" :with-header="false">
      <el-descriptions :title="tableTitle" :column="2" border>
        <el-descriptions-item label="餐台编号">{{ table.tableId }}</el-descriptions-item>
        <el-descriptions-item label="桌型">{{ table.tableType }}</el-descriptions-item>
        <el-descriptions-item label="使用状态">
          {{ ['待点菜', '用餐中', '待结账'].includes(table.tableStatus) ? '占用('+table.tableStatus+')' : table.tableStatus }}
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
/** ------------------全局导入区-------------------- */
import { ref, reactive, toRef, onMounted, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type{ TableDTO, QueryParams, RuleForm } from "@/views/store/table/types";
import { listAllTable, listTable, listTableByPage, getTableById,getTableByStatus, addTable, updateTable, deleteTable, deleteTableBatch } from '@/api/table'

onMounted(() => {
// 挂载后加载数据
getList()
})

/** ------------------数据查询区——表单-------------------- */
// 表单实例
const queryRef = ref<FormInstance>()

// 查询
const query = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 5,
  tableId: '',
  tableStatus: ''
})
const queryParams = toRef(query)

// 数据查询区--> 查询按钮
function handleQuery() {
queryParams.value.pageNum = 1
const params = {
    ...queryParams.value,
    tableStatus: queryParams.value.tableStatus === '占用' ? ['待点菜', '用餐中', '待结账'] : queryParams.value.tableStatus
  }
getList(params)
ElMessage.success(JSON.stringify(queryParams.value))
}

// 数据查询区--> 重置按钮
const resetQuery = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.resetFields()
getList()
}

/** ------------------数据展示区——表格-------------------- */

// 数据列表
const loading = ref<boolean>(false)  // table数据加载遮罩
const total = ref<number>(0) // table数据总数
const isEditMode = ref(false)

// table数据
const tableData = reactive<TableDTO[]>([]) 
const tables = toRef(tableData)

// 响应式餐桌数据
// const tables = ref<TableDTO[]>([])

// 加载数据
const getList = async (params?: any) => {
loading.value = true
const query = params || queryParams.value
/** 调用后端分页查询接口 */
listTableByPage(query).then(response => {
  tables.value = response.data.list.map(item => ({
    ...item,
    tableStatus: ['待点菜', '用餐中', '待结账'].includes(item.tableStatus) ? '占用' : item.tableStatus
  }))
  total.value = response.data.total
  loading.value = false
})
}

/** ------------------数据展示区：数据选择-------------------- */

const ids = ref<string[]>([]) // 表单勾选的id
const single = ref<boolean>(false) // 勾选1个
const multiple = ref<boolean>(false) // 勾选多个

// 数据展示区--> 勾选数据
function handleSelectionChange(selection: TableDTO[]) {
ids.value = selection.map((item:TableDTO) => item.tableId)
single.value = selection.length == 1
multiple.value = selection.length >= 1 

}

/** ------------------数据展示区：分页加载-------------------- */
// 分页--> 修改每页数据数（5｜10｜20｜30）
function handleSizeChange(val:number) {
queryParams.value.pageSize = val
getList()
}

//分页--> 修改当前页
function handleCurrentChange(val:number) {
queryParams.value.pageNum = val
getList()
}

/** ------------------数据编辑区——对话框+表单-------------------- */
// 表单数据
const formRef = ref<FormInstance>()

const formData = reactive<RuleForm>({
  tableId: '',
  tableType: '',
  tableStatus: '空闲'
})
const form  = toRef(formData)
const rules = reactive<FormRules<RuleForm>>({ // 表单验证规则
tableId: [
  { required: !isEditMode, message: '餐台编号不能为空', trigger: 'blur' },
],
tableType: [
  { required: true, message: '桌型不能为空', trigger: 'blur' },
],
})

// 对话框数据
const title = ref('') // 对话框标题
const open = ref(false) //对话框打开

// 数据编辑区-->提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate((valid, fields) => {
      if (valid) {
        const submitData = {
          ...form.value,
          // 如果是占用状态，默认设为"待点菜"
          tableStatus: form.value.tableStatus === '占用' ? '待点菜' : form.value.tableStatus
        }
        /** 调用后端新增和修改接口 */
        if (isEditMode.value) {
          updateTable(submitData).then((response) => {
            ElMessage({type: 'success',message: '修改数据成功'})
          })
        } else {
          addTable(submitData).then((response) => {
            ElMessage({type: 'success',message: '新增数据成功'})
          })
        }
        getList()
        open.value = false
        ElMessage.success(JSON.stringify(form.value))
      } else {
        console.log('表单验证未通过', fields) // 前台会自动提示errors
      }
  })
}

// 数据编辑区-->重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
// 数据编辑区-->取消按钮
function cancel(){
initForm()
open.value = false
}

/** ------------------数据操作区——按钮-------------------- */
// 清空或赋值表单数据
const initForm = () => {
// formRef.value?.resetFields() 
form.value = {
  tableId: '', // 确保 tableId 为空
  tableType: '',
  tableStatus: '空闲'
}
}

// 数据操作区--> 新增按钮
function handleAdd() {
isEditMode.value = false //标记为新增模式
initForm()
title.value = '新增餐台'
open.value = true
}

// 数据操作区区--> 修改按钮
const handleUpdate = async (row: TableDTO) => {
isEditMode.value = true
initForm()
  const id = row.tableId || ids.value[0]

    /** 调用后端id查询接口*/
getTableById(id).then((response) => {
  form.value = response.data
  title.value = '修改数据['+ id +']'
  open.value = true
})
}

// 数据操作区--> 删除按钮
async function handleDelete(row: any) {
const id = row.tableId
ElMessageBox.confirm('是否删除编号为' + id + '的数据?','警告')
  .then(() =>{
    return deleteTable(id)
  })
  .then(() => {
      getList()
      ElMessage({type: 'success',message: '删除成功'})
  })
  .catch(() => {})    
}

// 数据操作区--> 批量删除
async function handleDeleteBatch() {
const tableIds = ids.value
ElMessageBox.confirm('是否批量删除编号为' + tableIds + '的数据?','警告')
  .then(() => {
    return deleteTableBatch(tableIds)
  })
  .then(() => {
      getList()
      ElMessage({type: 'success',message: '批量删除成功',})
  })
  .catch(() => {})  
}

// 数据操作区-->抽屉查看数据
const drawer = ref<boolean>(false)
const tableTitle = ref<string>('');
const table = ref<TableDTO>({
tableId: '',
tableType: '',
tableStatus: '空闲'
})

// 数据操作区--> 查看按钮
function handleView(row: TableDTO) {
getTableById(row.tableId).then(response => {
  table.value = response.data
  tableTitle.value = '查看产品数据['+ row.tableId +']'
})
ElMessage.success(JSON.stringify(table.value))
drawer.value = true
}
</script>